package com.systop.cardecorate.admin.exception;

import com.systop.common.exception.BizCodeEnum;
import com.systop.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jsj
 * @date 2022/5/8
 * admin统一异常处理
 */

@Slf4j
@RestControllerAdvice(basePackages = "com.systop.cardecorate.admin.controller")
public class AdminExceptionControllerAdvice {
    // @ExceptionHandler(value = Exception.class)
    // public R handleValidException(Exception e){
    //     log.error("数据校验出现异常:{},异常类型:{}",e.getMessage(),e.getClass());
    //     return R.error();
    // }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现异常:{},异常类型:{}",e.getMessage(),e.getClass());
        //
        Map<String, String> errorMap = new HashMap<>();
        BindingResult errorResult = e.getBindingResult();
        errorResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        //返回错误到前台
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),
                BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleValidException(Throwable throwable){
        //打印错误信息
        log.error("错误：",throwable);
        //返回错误信息
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),
                BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
